import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import Service from '@/public/http/services';
import {
  Icon,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Radio,
  Upload,
  message,
  Table,
  Empty,
  Button,
} from 'antd';
//@ts-ignore
import LzEditor from 'react-lz-editor';
import style from './index.css';
import classnames from 'classnames';
import { DocumentType } from '@/public/constant/enums';
import TPage from '@/modules/TPage';
const { TextArea } = Input;
const { Option } = Select;
const FileModal: React.FC<any> = ({ visible, title, onOK, onCancel, form, dispatch,parentid }) => {
  const [curAllExperts, setCurAllExperts] = useState([]);
  const [curPage, setCurPage] = useState(1);
  const [curPage2, setCurPage2] = useState(1);
  const [curPage3, setCurPage3] = useState(1);
  const [curName, setCurName] = useState("");
  const [curName2, setCurName2] = useState("");
  const [curName3, setCurName3] = useState("");
  const pageSize = 10;
  const [list, setList] = useState([]);
  const [total,setTotal] = useState(0)
  const [list2, setList2] = useState([]);
  const [total2,setTotal2] = useState(0)
  const [list3, setList3] = useState([]);
  const [total3,setTotal3] = useState(0)
  const { Column } = Table;
  function queryAllExperts() {
    return Service.queryAllExpert()
  }
  useEffect(() => {
    if (visible) {
      queryCurres()
      queryunbind()
    }
  }, [ visible])
  useEffect(() => {
    queryunbind()
  }, [ curName,curName2])
  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 14 },
  }

  const { getFieldDecorator } = form;

  const [loading, setLoading] = useState(false);

  const [curFileList, setCurFileList] = useState([]);
  const [curTab, setCurTab] = useState(1);


  const uploadSuccess = (file, fileObj) => {
    setLoading(false);
    const { uid, name } = fileObj;
    setCurFileList(curFileList.concat([{
      uid,
      name,
      url: curFileUrl,
    }] as any));
  }

  const handleChange = (file) => { }

  const [curActionUrl, setCurActionUrl] = useState();
  const [curUploadData, setCurUploadData] = useState({});
  const [curFileUrl, setCurUrl] = useState('');
  const beforeUpload = async (file, fileList) => {
    setLoading(true);
    const result = await Service.uploadFileDirect();
    const { host, policy, accessid, signature } = result;
    setCurActionUrl(host);
    const timetamp = new Date().getTime();
    const key = timetamp + '.' + file.name.split('.').pop()
    setCurUrl(host + '/' + key)
    setCurUploadData({
      key,
      policy,
      OSSAccessKeyId: accessid,
      success_action_status: '200',
      signature
    });
    return true;
  }

  const removeSuccess = (file) => {
    let list = [];
    for (const item of curFileList) {
      if ((item as any).uid !== file.uid) list.push(item);
    }
    setCurFileList(list);
  }
  /**
   * @desc 文章插图上传配置
   */
  const upload: any = {
    name: 'file',
    action: curActionUrl,//上传接口，成功后返回该图片服务器地址
    listType: 'picture-card',
    headers: {
      authorization: 'authorization-text',
    },
    onSuccess: uploadSuccess,
    onChange: handleChange,
    beforeUpload: beforeUpload,
    onRemove: removeSuccess,
    data: curUploadData,
    multiple: true
  }

  const [searchList, setSearchList] = useState([]);
  const [curitem, setCuritem] = useState(0);
  const [searchvalue,setSearchvalue] = useState("");
  const [curzl,setCurzl] = useState([]);
  const [curvideo,setCurVideo] = useState([]);
  const [curaudio,setCuraudio] = useState([]);
  var timmer;

  const handleQueryb = (query) => {
    setCurPage(1);
    setCurName(query);
  }

  const handleQueryb2 = (query) => {
    setCurPage2(1);
    setCurName2(query);
  }

  const handleQueryb3 = (query) => {
    setCurPage3(1);
    setCurName3(query);
  }

  const changesearch = (e)=>{
    var query:String = e.target.value
    setSearchvalue(query as any)
    clearTimeout(timmer)
    if(query == ""){
      setSearchList([])
      return
    }

    timmer = setTimeout(rest=>{
      Service.queryBindResource({name:query}).then((res) => {
        setSearchList(res as any)
      })
    },500)

  }

  const bindzl = (id,e)=>{
    setCuritem(id)
    setSearchList([])
    setSearchvalue("")
    var binded = false

    if(binded){
      for(let item in curzl){
        if(item[id] == id){
          binded = true
          return
        }
      }
      return message.error("数据已绑定", 4)
    }
    Service.BindzjResource( {resId:id, subjectId:parentid}).then((res) => {
      queryCurres()
      queryunbind()
    })
  }

  const queryCurres =()=>{
    Service.queryzjResource( { subjectId:parentid,type:1}).then((res) => {
      setCurzl(res as any)
    })

    Service.queryzjResource( { subjectId:parentid,type:2}).then((res) => {
      setCurVideo(res as any)
    })

    Service.queryzjResource( { subjectId:parentid,type:3}).then((res) => {
      setCuraudio(res as any)
    })
  }

  const queryunbind = ()=>{
    Service.queryUnbindResource( { pageNum:curPage,pageSize:pageSize,name:curName,subjectId:parentid,type:1}).then((res) => {
      setList(res.list as any)
      setTotal(res.total as any)
    })

    Service.queryUnbindResource( { pageNum:curPage,pageSize:pageSize,name:curName,subjectId:parentid,type:2}).then((res) => {
      setList2(res.list as any)
      setTotal2(res.total as any)
    })
    Service.queryUnbindResource( { pageNum:curPage,pageSize:pageSize,name:curName,subjectId:parentid,type:3}).then((res) => {
      setList3(res.list as any)
      setTotal3(res.total as any)
    })
  }

  const renderActions =
    (record: any) => {
      return (
        <>
          <Button className={style.mr8} type={'primary'} onClick={() => { bindzl(record.id,event) }}>添加绑定</Button>
        </>
      );
    }

  const renderActions2 =
    (record: any) => {
      return (
        <>
          <Button className={style.mr8} type={'primary'} onClick={() => { deletebind(record.relId,event) }}>取消绑定</Button>
        </>
      );
    }

  const renderActions3 =
    (record: any) => {
      return (
        <>
          第<Input type="text" defaultValue={record.order}  onBlur={() => { changesort(record.relId,event) }} className="sortinput"></Input><span className="sorttxt">节课</span>
          <Button className={style.mr8} type={'primary'} onClick={() => { deletebind(record.relId,event) }}>取消绑定</Button>
        </>
      );
    }

  const changesort = (id,e)=>{
    Service.changesort( { resRelId:id,order:e.target.value,subjectId:parentid}).then((res) => {
      queryCurres()
    })
  }

  const deletebind = (id,e)=>{
    Service.deletezlBind( {id:id}).then((res) => {
      queryCurres()
      queryunbind()
    })
  }

  const changetab = (tab,e)=>{
    setCurTab(tab)
  }

  return (
    <Modal
      visible={visible}
      title={title}
      okText={'确定'}
      cancelText={'取消'}
      onOk={() => {
        onCancel(form)
      }}
      onCancel={() => {
        onCancel(form)
      }}

      width={'65%'}
    >
      {
        /**
         *  <Form.Item {...formItemLayout} label={'资料类型'}>
         {
                    getFieldDecorator('type', {
                        initialValue: '',
                        rules: [{ required: true, message: '请选择资料类型' }],
                    })(<Select className={style.w220} placeholder={'请选择资料类型'}>
                    <Option value={1}>文库资料</Option>
                    <Option value={2}>视频资料</Option>
                    <Option value={3}>音频资料</Option>
                </Select>)
                }
         </Form.Item>
         */
      }

      <div className="bindzlbody">
        <div className="bindtab">
          <div className={ curTab == 1?"tab active": "tab"} onClick={e=>changetab(1,e)}>已绑定文档</div>
          <div className={ curTab == 2?"tab active": "tab"} onClick={e=>changetab(2,e)}>未绑定文档</div>
          <div className={ curTab == 3?"tab active": "tab"} onClick={e=>changetab(3,e)}>已绑定视频</div>
          <div className={ curTab == 4?"tab active": "tab"} onClick={e=>changetab(4,e)}>未绑定视频</div>
          <div className={ curTab == 5?"tab active": "tab"} onClick={e=>changetab(5,e)}>已绑定音频</div>
          <div className={ curTab == 6?"tab active": "tab"} onClick={e=>changetab(6,e)}>未绑定音频</div>
        </div>
        <div className={ curTab == 1?"tabp active": "tabp"}>
          <Table
            className={classnames(style.mt16, style.document_list)}
            locale={{ emptyText: <Empty description={'无数据'} /> }}
            dataSource={curzl}
            pagination={ false }
            rowKey={(record: any) => record.id}
            scroll={{ x: 2000 }}
          >
            <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
            <Column title={'资料名称'} width={320} key={'name'}
                    render={(value, record: any) => {
                      return <span className={style.mainPicUnit}>
                < img src={record.coverImg} />
                        {record.name}
              </span>
                    }} />
            <Column title={'作者'} key={'author'}
                    render={(value, record: any) => {
                      return <span className={style.thumbnail}>
                < img src={record.authorPortrait} />
                        {record.author}
              </span>
                    }}
            />
            <Column title={'资料类型'} dataIndex={'type'} key={'type'} render={value => DocumentType[value]} />
            <Column title={'资料大小(MB)'} dataIndex={'size'} key={'size'} />
            <Column title={'关键词'} dataIndex={'keywords'} key={'keywords'} />
            <Column title={'下载量'} key={'count'} />
            <Column title={'资料地址'} dataIndex={'url'} key={'url'} width={280} render={value => <a href={value} className={style['file-link']}>{value}</a>} />
            <Column title={'更新时间'} dataIndex={'uTime'} key={'uTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'操作'} key={'act'} render={renderActions2} fixed={'right'} />
          </Table>
          <div className="clearboth"></div>
        </div>
        <div className={ curTab == 3?"tabp active": "tabp"}>
          <Table
            className={classnames(style.mt16, style.document_list)}
            locale={{ emptyText: <Empty description={'无数据'} /> }}
            dataSource={curvideo}
            pagination={ false }
            rowKey={(record: any) => record.id}
            scroll={{ x: 2000 }}
          >
            <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
            <Column title={'资料名称'} width={320} key={'name'}
                    render={(value, record: any) => {
                      return <span className={style.mainPicUnit}>
                < img src={record.coverImg} />
                        {record.name}
              </span>
                    }} />
            <Column title={'作者'} key={'author'}
                    render={(value, record: any) => {
                      return <span className={style.thumbnail}>
                < img src={record.authorPortrait} />
                        {record.author}
              </span>
                    }}
            />
            <Column title={'资料类型'} dataIndex={'type'} key={'type'} render={value => DocumentType[value]} />
            <Column title={'资料大小(MB)'} dataIndex={'size'} key={'size'} />
            <Column title={'关键词'} dataIndex={'keywords'} key={'keywords'} />
            <Column title={'下载量'} key={'count'} />
            <Column title={'资料地址'} dataIndex={'url'} key={'url'} width={280} render={value => <a href={value} className={style['file-link']}>{value}</a>} />
            <Column title={'更新时间'} dataIndex={'uTime'} key={'uTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'操作'} key={'act'} render={renderActions3} fixed={'right'} />
          </Table>
          <div className="clearboth"></div>
        </div>
        <div className={ curTab == 4?"tabp active": "tabp"}>
          <TPage.Search
            placeholder={'请输入资料名称，可按回车键搜索'}
            onSearch={handleQueryb2}
          />
          <Table
            className={classnames(style.mt16, style.document_list)}
            locale={{ emptyText: <Empty description={'无数据'} /> }}
            dataSource={list2}
            pagination={{ total2, current: curPage2, pageSize, onChange: setCurPage2 }}
            rowKey={(record: any) => record.id}
            scroll={{ x: 2000 }}
          >
            <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
            <Column title={'资料名称'} width={320} key={'name'}
                    render={(value, record: any) => {
                      return <span className={style.mainPicUnit}>
                < img src={record.coverImg} />
                        {record.name}
              </span>
                    }} />
            <Column title={'作者'} key={'author'}
                    render={(value, record: any) => {
                      return <span className={style.thumbnail}>
                < img src={record.authorPortrait} />
                        {record.author}
              </span>
                    }}
            />
            <Column title={'资料类型'} dataIndex={'type'} key={'type'} render={value => DocumentType[value]} />
            <Column title={'资料大小(MB)'} dataIndex={'size'} key={'size'} />
            <Column title={'关键词'} dataIndex={'keywords'} key={'keywords'} />
            <Column title={'下载量'} key={'count'} />
            <Column title={'资料地址'} dataIndex={'url'} key={'url'} width={280} render={value => <a href={value} className={style['file-link']}>{value}</a>} />
            <Column title={'更新时间'} dataIndex={'uTime'} key={'uTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'操作'} key={'act'} render={renderActions} fixed={'right'} />
          </Table>
          <div className="clearboth"></div>
        </div>

        <div className={ curTab == 2?"tabp active": "tabp"}>
          <TPage.Search
            placeholder={'请输入资料名称，可按回车键搜索'}
            onSearch={handleQueryb}
          />
          <Table
            className={classnames(style.mt16, style.document_list)}
            locale={{ emptyText: <Empty description={'无数据'} /> }}
            dataSource={list}
            pagination={{ total, current: curPage, pageSize, onChange: setCurPage }}
            rowKey={(record: any) => record.id}
            scroll={{ x: 2000 }}
          >
            <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
            <Column title={'资料名称'} width={320} key={'name'}
                    render={(value, record: any) => {
                      return <span className={style.mainPicUnit}>
                < img src={record.coverImg} />
                        {record.name}
              </span>
                    }} />
            <Column title={'作者'} key={'author'}
                    render={(value, record: any) => {
                      return <span className={style.thumbnail}>
                < img src={record.authorPortrait} />
                        {record.author}
              </span>
                    }}
            />
            <Column title={'资料类型'} dataIndex={'type'} key={'type'} render={value => DocumentType[value]} />
            <Column title={'资料大小(MB)'} dataIndex={'size'} key={'size'} />
            <Column title={'关键词'} dataIndex={'keywords'} key={'keywords'} />
            <Column title={'下载量'} key={'count'} />
            <Column title={'资料地址'} dataIndex={'url'} key={'url'} width={280} render={value => <a href={value} className={style['file-link']}>{value}</a>} />
            <Column title={'更新时间'} dataIndex={'uTime'} key={'uTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'操作'} key={'act'} render={renderActions} fixed={'right'} />
          </Table>
          <div className="clearboth"></div>
        </div>

        <div className={ curTab == 5?"tabp active": "tabp"}>
          <Table
            className={classnames(style.mt16, style.document_list)}
            locale={{ emptyText: <Empty description={'无数据'} /> }}
            dataSource={curaudio}
            pagination={ false }
            rowKey={(record: any) => record.id}
            scroll={{ x: 2000 }}
          >
            <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
            <Column title={'资料名称'} width={320} key={'name'}
                    render={(value, record: any) => {
                      return <span className={style.mainPicUnit}>
                < img src={record.coverImg} />
                        {record.name}
              </span>
                    }} />
            <Column title={'作者'} key={'author'}
                    render={(value, record: any) => {
                      return <span className={style.thumbnail}>
                < img src={record.authorPortrait} />
                        {record.author}
              </span>
                    }}
            />
            <Column title={'资料类型'} dataIndex={'type'} key={'type'} render={value => DocumentType[value]} />
            <Column title={'资料大小(MB)'} dataIndex={'size'} key={'size'} />
            <Column title={'关键词'} dataIndex={'keywords'} key={'keywords'} />
            <Column title={'下载量'} key={'count'} />
            <Column title={'资料地址'} dataIndex={'url'} key={'url'} width={280} render={value => <a href={value} className={style['file-link']}>{value}</a>} />
            <Column title={'更新时间'} dataIndex={'uTime'} key={'uTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'操作'} key={'act'} render={renderActions3} fixed={'right'} />
          </Table>
          <div className="clearboth"></div>
        </div>
        <div className={ curTab == 6?"tabp active": "tabp"}>
          <TPage.Search
            placeholder={'请输入资料名称，可按回车键搜索'}
            onSearch={handleQueryb3}
          />
          <Table
            className={classnames(style.mt16, style.document_list)}
            locale={{ emptyText: <Empty description={'无数据'} /> }}
            dataSource={list3}
            pagination={{ total3, current: curPage3, pageSize, onChange: setCurPage3 }}
            rowKey={(record: any) => record.id}
            scroll={{ x: 2000 }}
          >
            <Column title={'编号ID'} width={64} dataIndex={'id'} key={'id'} />
            <Column title={'资料名称'} width={320} key={'name'}
                    render={(value, record: any) => {
                      return <span className={style.mainPicUnit}>
                < img src={record.coverImg} />
                        {record.name}
              </span>
                    }} />
            <Column title={'作者'} key={'author'}
                    render={(value, record: any) => {
                      return <span className={style.thumbnail}>
                < img src={record.authorPortrait} />
                        {record.author}
              </span>
                    }}
            />
            <Column title={'资料类型'} dataIndex={'type'} key={'type'} render={value => DocumentType[value]} />
            <Column title={'资料大小(MB)'} dataIndex={'size'} key={'size'} />
            <Column title={'关键词'} dataIndex={'keywords'} key={'keywords'} />
            <Column title={'下载量'} key={'count'} />
            <Column title={'资料地址'} dataIndex={'url'} key={'url'} width={280} render={value => <a href={value} className={style['file-link']}>{value}</a>} />
            <Column title={'更新时间'} dataIndex={'uTime'} key={'uTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'创建时间'} dataIndex={'createTime'} key={'createTime'} width={200}  render={(value) => moment(value).format('YYYY-MM-DD hh:mm:ss')} />
            <Column title={'操作'} key={'act'} render={renderActions} fixed={'right'} />
          </Table>
          <div className="clearboth"></div>
        </div>

      </div>
    </Modal>
  );
}
const WrappedCreateModal = Form.create<any>({ name: 'modalForm' })(FileModal);
export default connect((state: any) => {
  return {}
})(WrappedCreateModal);
